const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const bodyParser = require('body-parser');

const urlencodeParser = bodyParser.urlencoded({
    extended: true,
    limit: '50mb'
});
const connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '12345678',
    database: 'internetcafe'
});
connection.connect(function (err) {
    if (err) {
        console.error('连接失败: ' + err.stack);
        return;
    }
    console.log('连接成功 id ' + connection.threadId);
})
router.get("/selectconsume", function (req, res) {

    connection.query('select consume.*,user.*,computer.*  from consume,user,computer where user.id=consume.userid and computer.no= consume.computerid  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
router.get("/selectconsumeByUser", function (req, res) {
    let data = req.query
    console.log(data.kindid)
    connection.query('select * from user where ismember=  "' + data.kindid + '"  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
router.get('/adduser', function (req, res) {
    let data = req.query;
    console.log(data)
    let tempdata = {
        id: null,
        username: data.username,
        pwd: data.pwd,
        idcard: data.idcard,
        balance: data.balance,
        ismember: data.ismember,
    }
    //检验是否为空
    if (tempdata.id == '' || tempdata.username == '' || tempdata.pwd == '' || tempdata.idcard == '') {
        res.jsonp({
            code: 0,
            msg: '你输入信息不能为空。'
        })
        return;
    }
    connection.query('select * from user where idcard=  "' + tempdata.idcard + '"  ', (err, result) => {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else if (result[0] != null) {
            res.jsonp({
                msg: "该身份证号码的用户已经存在",
                code: 0
            })
        } else {
            connection.query('insert into user set ?', tempdata, (err, result) => {
                if (err) {
                    console.log(err);
                    res.jsonp({
                        fail: 1
                    })
                } else {
                    res.jsonp({
                        code: 1,
                        result: data
                    })
                }
            })
        }
        return;

    })

})

module.exports = router;